from django.shortcuts import render
from rest_framework.viewsets import GenericViewSet, ViewSet
from .serializer import PaySerializer
from utils.common_reponse import APIResponse
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from .models import Order
from libs.al_pay import alipay
from rest_framework.response import Response
from utils.common_logger import logger


class PayOrderView(GenericViewSet):
    serializer_class = PaySerializer
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 获取支付链接
        pay_url = serializer.context.get('pay_url')
        return APIResponse(msg='下单成功', pay_url=pay_url)


class PaySuccessView(ViewSet):
    # api/v1/order/success/check_order/
    @action(methods=['GET'], detail=False)
    def check_order(self, request, *args, **kwargs):
        # 1 取出订单 id号
        out_trade_no = request.query_params.get('out_trade_no')
        # 2 去数据库校验订单
        order = Order.objects.filter(out_trade_no=out_trade_no, order_status=1).first()
        if order:  # 3 订单状态：已支付---》返回成功
            return APIResponse(msg='支付成功，开始学习之旅')
        else:  # 4 订单状态：未支付---》返回失败
            return APIResponse(code=101, msg='暂未收到付款，请稍后再试')

    # 需要支付宝post回调，修改订单状态
    @action(methods=['POST'], detail=False)
    def check_al_order(self, request, *args, **kwargs):
        # 1 取出支付宝给我们的数据--》request.data--->编码格式是：urlencoded--》QueryDict--》不允许修改
        # 2 验签--》sdk验
        # 3 成功就修改订单状态
        # 4 返回给支付宝--》固定格式  24小时内，回调8次
        try:
            # json编码 -->是字典
            # urlencoded--》querydict---》dict()----》纯字典
            # 支付宝回调编码是：urlencoded
            result_data = request.data.dict()  # 把request.data  ---> 转成字典格式
            out_trade_no = result_data.get('out_trade_no')  # 订单号
            trade_no = result_data.get('trade_no')  # 支付宝流水号
            signature = result_data.pop('sign')  # pop出来
            pay_time = result_data.pop('notify_time', '2024-06-01')

            result = alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                # 完成订单修改：订单状态、流水号、支付时间
                Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1, trade_no=trade_no,
                                                                       pay_time=pay_time)
                # 完成日志记录
                logger.warning('%s订单支付成功' % out_trade_no)
                return Response('success')
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        return Response('failed')
